// pages/bookshelf/bookshelf.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    isDark: '',
    bookShelfData: [],
    isEdit: false,
    userInfo:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    wx.setNavigationBarTitle({
      title: '书架',
    })
    let storageDark = wx.getStorageSync('storageDark') ? wx.getStorageSync('storageDark') : false
    this.setData({
      isDark: storageDark
    })

    this.getData()
    this.getBook()
  },

  changeIsEdit() {
    this.setData({
      isEdit: !this.data.isEdit
    })
  },

  delBookShelfFn(e) {

    wx.cloud.callFunction({
      name: 'delBookShelf',
      data: {
        bookId: e.target.dataset.id,
      }
    }).then(() => {
      Toast.success('已移出书架');
      console.log(e.target.dataset.id);
      let arr = this.data.bookShelfData

      arr = arr.filter(t => t.bookId != e.target.dataset.id)

      this.setData({
        bookShelfData: arr
      })

    })
  },

  delAllBookShel() {

    Dialog.confirm({
      title: '清空',
      message: '是否全部清空?',
    })
      .then(() => {

        wx.cloud.callFunction({
          name: 'delBookShelf',
          data: {
            type: 'bookShelf',
          }
        }).then(() => {
          Toast.success('已清空书架');
        })

        
      this.setData({
        bookShelfData: []
      })

      })



  },

  getData() {

    wx.request({
      url: 'https://app.kujiang.com/v1/home/bookshelf_recommend',
      success: ({ data }) => {

        this.setData({
          dataList: data.body
        })

        console.log(this.data.dataList);
      }
    })

  },


  getBook() {
   let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      return
    }

    this.setData({
      userInfo
    })

    wx.cloud.callFunction({
      name: 'getBook',
      data: {
        type: 'bookShelf',
      }
    }).then((res) => {
      this.setData({
        bookShelfData: res.result.currentList
      })
      console.log(this.data.bookShelfData);
      // if (res.result.currentList.length != 0) {
      //   this.setData({
      //     isBookShelf: true
      //   })
      // }

    })
  },


  goToHistory(){
    wx.navigateTo({
      url: '/pages/history/history',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})